package langchain4j.controller;

import dev.langchain4j.agent.tool.P;
import langchain4j.bean.Appointment;
import langchain4j.entity.User;
import langchain4j.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class LoginController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody User user) {
        String idCard = user.getIdCard();
        String password = user.getPassword(); // 明文密码
        Map<String, Object> response = new HashMap<>();

        User dbUser = userService.findUserByIdCardAndPassword(idCard, password);
        if (dbUser == null) {
            response.put("code", 401);
            response.put("message", "用户名或密码错误");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }

        response.put("code", 200);
        response.put("message", "登录成功");
        response.put("data", dbUser); // 返回用户信息（需过滤敏感字段）
        return ResponseEntity.ok(response);
    }

    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();
        boolean register = userService.register(user);
        if (!register) {
            response.put("code", 401);
            response.put("message", "注册失败请联系管理员");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }else {
            response.put("code", 200);
            response.put("message", "注册成功");
            return ResponseEntity.ok(response);
        }
    }

    @PostMapping("/resetPass")
    public ResponseEntity<Map<String, Object>> resetPass(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();
        try {
            userService.resetPass(user);
            response.put("code", 200);
            response.put("message", "密码找回成功");
            return ResponseEntity.ok(response);
        } catch (ResponseStatusException e) {
            response.put("code", e.getStatusCode().value());
            response.put("message", e.getReason());
            return ResponseEntity.status(e.getStatusCode()).body(response);
        } catch (Exception e) {
            response.put("code", 401);
            response.put("message", "找回失败请联系管理员");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }
}
